<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>webgl缩放和旋转</title>
    <script src="lib/webgl-debug.js"></script>
    <script src="lib/webgl-utils.js"></script>
    <script src="lib/cuon-utils.js"></script>
    <script src="lib/cuon-matrix.js"></script>
</head>

<body onload="main()" onclick="click">
    <canvas width="800" height="800" id="canvas"></canvas>
</body>

<script>
    var vs = `
    attribute vec4 a_Position;
    uniform float u_SinB,u_CosB;
    void main(){
        gl_Position.x = a_Position.x*u_CosB-a_Position.y*u_SinB;
        gl_Position.y = a_Position.x*u_SinB+a_Position.y*u_CosB;
        gl_Position.z = a_Position.z;
        gl_Position.w = a_Position.w;
    }
    `;
    var fs = `
    void main(){
        gl_FragColor = vec4(1.0,0.5,0.5,1.0);
    }
    `;

    var angle = 60;

    function click() {
        angle++;
        main();
    }

    function main() {
        var canvas = document.getElementById("canvas");
        draw();
        canvas.onmousedown = function(event) {
            click();
        }
    }

    function draw() {
        var canvas = document.getElementById("canvas");
        var gl = getWebGLContext(canvas);
        if (!initShaders(gl, vs, fs)) {
            console.log("初始化着色器失败");
            return;
        }
        var n = initVertexBuffer(gl);
        if (n < 0) {
            console.log("无法获取顶点相关的数据");
            return;
        }
        var radin = Math.PI * angle / 180;
        var cosB = Math.cos(radin);
        var sinB = Math.sin(radin);

        var u_CosB = gl.getUniformLocation(gl.program, "u_CosB");
        var u_SinB = gl.getUniformLocation(gl.program, "u_SinB");
        if (u_CosB < 0 || u_SinB < 0) {
            console.log("无法获取变量储存位置");
            return;
        }

        gl.uniform1f(u_CosB, cosB);
        gl.uniform1f(u_SinB, sinB);

        // 清除颜色缓冲区
        gl.clearColor(0, 0, 0, 1);
        // 清除颜色缓冲区
        gl.clear(gl.COLOR_BUFFER_BIT);
        // 绘制三级形
        gl.drawArrays(gl.TRIANGLE_FAN, 0, n);
    }


    function initVertexBuffer(gl) {

        var verties = new Float32Array([-0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5]);
        var n = 4;
        // 创建顶点缓存区
        var vertexBuffer = gl.createBuffer();
        // 绑定缓冲区
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
        //想缓冲区写入顶点数据
        gl.bufferData(gl.ARRAY_BUFFER, verties, gl.STATIC_DRAW);
        var a_Position = gl.getAttribLocation(gl.program, "a_Position");
        //将缓冲区分配给 a_Positon 属性
        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
        // 闭合缓冲区
        gl.enableVertexAttribArray(a_Position);
        return n;
    }
</script>

</html>